// import { API } from "./api";

// const BASE_URL = 'https://www.filecashchain.io'
const BASE_URL = 'http://192.168.16.113:8081'
function _baseMixins(base) {
    return function (api) {
        return function (api2) {
            return base + api + api2
        }
    }
}

const usersMixins = _baseMixins(BASE_URL)('/v1/users')
const baseMixins = _baseMixins(BASE_URL)('')

class API {
    static async sendCode(params) {
        const res = await _post(usersMixins('/sendCaptcha'), params)
        const resJson = await res.json()
        return resJson
    }
    static async getGeetest() {
        try {
            const res = await _get(baseMixins(`/v1/validate/registerGeetest?t=${Date.now()}`))
            const resJson = await res.json()
            return resJson
        } catch (e) {
            alert(e)
        }
    }
}
function _post(api, data = {}, method = 'POST') {
    const options = {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        method: method,
        body: JSON.stringify(data)
    }
    return fetch(api, options)
}

function _get(api) {
    return fetch(api)
}


let alreadySent = false
async function sendCode(params) {
    let {to, type, geetestChallenge, geetestValidate, geetestSeccode, gtServerStatus, geetestUserId, alreadySent, second } = params
    // type: 1注册 2绑定 3设置 4重置登陆密码 5重置资金密码 6提币验证码
    // to: 手机或者邮箱，手机加+区号
    // lang: 1cn 2tw 3en
    // gtServerStatus：1成功 0失败（走另外的流程）
    // alreadySent: 用于是否发送了的验证码的倒计时，防止多次调用
    alreadySent = true
    second = second || 'second'

    let sendData = {}
    sendData.to = to
    sendData.type = type
    sendData.lang = 1
    sendData.geetestChallenge = geetestChallenge
    sendData.geetestSeccode = geetestSeccode
    sendData.gtServerStatus = '' + gtServerStatus
    sendData.geetestValidate = geetestValidate
    sendData.geetestUserId = geetestUserId
    let result = await API.sendCode(sendData)
    window.postMessage('send')
}
async function GTvalidAndSendCode() {
    // let checkItemArr = checkItem.split('.')
    let lang = 'cn'
    let data = await API.getGeetest()
    if (data.success === 1) { // 先向后台请求gt的必要信息
        // 初始化gt
        window.initGeetest({
            gt: data.gt,
            challenge: data.challenge,
            offline: !data.success,
            new_captcha: true,
            product: 'bind', // bind是隐藏点击登陆验证的按钮
            lang: lang
        }, function (captchaObj) {
            // 初始化gt成功
            captchaObj.appendTo('#captcha')
            // captchaObj.verify();
            captchaObj.onReady(function () {
                // document.querySelector(target).addEventListener('click', () => {
                //     captchaObj.verify()
                // })
                setTimeout(() => {
                    captchaObj.verify()
                })
            })
            captchaObj.onSuccess(function () {
                // let item = self[checkItemArr[0]][checkItemArr[1]]
                let result = captchaObj.getValidate()// 获取跟后台二次验证所需的参数
                // 让服务器发送验证码
                // sendCode('+86', result.geetest_challenge, result.geetest_validate, result.geetest_seccode, data.success, data.user_id)
                sendCode( {
                    to: window.to,
                    type: window.type,
                    geetestChallenge: result.geetest_challenge,
                    geetestValidate: result.geetest_validate,
                    geetestSeccode: result.geetest_seccode,
                    gtServerStatus: data.success,
                    geetestUserId: data.user_id,
                    alreadySent: false,
                    second: 60 }
            )
            })
            captchaObj.onError(function () {
                // self.$notify({
                //     title: 'error',
                //     message: 'error',
                //     type: 'error',
                //     duration: 0,
                //     showClose: true
                // })
            })
        })
    } else {
        // self.$notify({
        //     title: 'error',
        //     message: 'error',
        //     type: 'error',
        //     duration: 0,
        //     showClose: true,
        //     offset: 8
        // })
    }
}
// 提交请求
// async function doExtract() {
//     if (this.ruleForm.amount === '' || this.ruleForm.address === '' || this.ruleForm.verifyCode === '' || !this.ruleForm.verifyChecked) {
//         // this.$notify({
//         //     message: '表单信息不正确！',
//         //     type: 'error',
//         //     duration: 5000,
//         //     showClose: true,
//         //     offset: 90,
//         //     title: ''
//         // })
//         return
//     }
//     const { amount, address, verifyCode, verifyChecked } = this.ruleForm
//     const res = await API.doExtract({
//         openId: window.localStorage.getItem('fcc_front_openid'),
//         amount,
//         address,
//         verify: verifyCode,
//         key: this.sendNumber
//     })
//     if (res.code === 200) {
//         // 提交成功
//         this.$notify({
//             message: '提交成功，等待审核',
//             type: 'success',
//             duration: 3000,
//             showClose: true,
//             offset: 90,
//             title: ''
//         })
//         setTimeout(() => {
//             this.$router.push({
//                 name: 'mill'
//             })
//         }, 3000)
//     }
// },
GTvalidAndSendCode()
